define([
    "UtilDir/util",
    "UtilDir/tool",
    "UtilDir/org/selectOrg",
    "UtilDir/searchBlock",
    "static/app/hddc/hddccjcommon/hddccjprojectmethod",
    "Date", "DateCN", "css!DateCss",
    "EasyUI", "EasyUI-lang"
], function (Util, Tool, SelectOrg, SearchBlock, hddccjprojectmethod) {

    var sysPath = getServer() + "/static/app/hddc/hddccjproject";

    var hddcCjProjectFormHtml = sysPath + "/views/hddcCjProjectForm.html";
    var getHddcCjProjectController = function () {
        return getServer() + "/hddc/hddcCjProjects";
    };

    /**
     * 页面初始化
     */
    var init = function () {
        initSearchBlock();
        queryBtnBind();
        //initProvinceSelect();
        //initCitySelect();
        //initAreaSelect();
        initcreateProvince();
        createHddcCjProjectGrid();
    };
    var initProvinceSelect = function () {
        $.ajax({
            url: getHddcCjProjectController() + "/getValidDictItemsByDictCode/" + "",
            type: "get",
            success: function (data) {
                var mySelect = document.getElementById("provinceSelect");
                mySelect.add(new Option("请选择", ''), 0);
                for (var i = 0; i < data.length; i++) {
                    var name = data[i].dictItemName;
                    var code = data[i].dictItemCode;
                    mySelect.add(new Option(name, code));
                }
            }
        });
    };
    var initCitySelect = function () {
        $.ajax({
            url: getHddcCjProjectController() + "/getValidDictItemsByDictCode/" + "",
            type: "get",
            success: function (data) {
                var mySelect = document.getElementById("citySelect");
                mySelect.add(new Option("请选择", ''), 0);
                for (var i = 0; i < data.length; i++) {
                    var name = data[i].dictItemName;
                    var code = data[i].dictItemCode;
                    mySelect.add(new Option(name, code));
                }
            }
        });
    };
    var initAreaSelect = function () {
        $.ajax({
            url: getHddcCjProjectController() + "/getValidDictItemsByDictCode/" + "",
            type: "get",
            success: function (data) {
                var mySelect = document.getElementById("areaSelect");
                mySelect.add(new Option("请选择", ''), 0);
                for (var i = 0; i < data.length; i++) {
                    var name = data[i].dictItemName;
                    var code = data[i].dictItemCode;
                    mySelect.add(new Option(name, code));
                }
            }
        });
    };

    var initProvinceSelectFrom = function () {
        $.ajax({
            url: getHddcCjProjectController() + "/getValidDictItemsByDictCode/" + "",
            type: "get",
            success: function (data) {
                var mySelect = document.getElementById("province");
                mySelect.add(new Option("请选择", ''), 0);
                for (var i = 0; i < data.length; i++) {
                    var name = data[i].dictItemName;
                    var code = data[i].dictItemCode;
                    mySelect.add(new Option(name, code));
                }
            }
        });
    };
    var initCitySelectFrom = function () {
        $.ajax({
            url: getHddcCjProjectController() + "/getValidDictItemsByDictCode/" + "",
            type: "get",
            success: function (data) {
                var mySelect = document.getElementById("city");
                mySelect.add(new Option("请选择", ''), 0);
                for (var i = 0; i < data.length; i++) {
                    var name = data[i].dictItemName;
                    var code = data[i].dictItemCode;
                    mySelect.add(new Option(name, code));
                }
            }
        });
    };
    var initAreaSelectFrom = function () {
        $.ajax({
            url: getHddcCjProjectController() + "/getValidDictItemsByDictCode/" + "",
            type: "get",
            success: function (data) {
                var mySelect = document.getElementById("area");
                mySelect.add(new Option("请选择", ''), 0);
                for (var i = 0; i < data.length; i++) {
                    var name = data[i].dictItemName;
                    var code = data[i].dictItemCode;
                    mySelect.add(new Option(name, code));
                }
            }
        });
    };
    var createPersonIdsUserSelectFrom = function () {
        SelectOrg.init({
            id: "personIdsName",
            multi: true,
            title: "请选择用户",
            hideTag: true,
            tagType: ["user"],
            callback: function (data) {
                
                if (data.user.length == 0) {
                    Util.alert("请选择用户");
                    return;
                }else{
                    var userIds = "";
                    var userNames = "";
                    for(var i=0;i<data.user.length;i++){
                        userIds += (data.user[i].userId + ",");
                        userNames += (data.user[i].userName + ",");
                    }
                }
                
                userIds = userIds.slice(0,userIds.length-1);
                userNames = userNames.slice(0,userNames.length-1);
                $("#personIds").val(userIds);
                $("#personIdsName").val(userNames);
            }
        });
    };

    var initSearchBlock = function () {
        SearchBlock.init("searchBlock");
    };
    var queryBtnBind = function () {
        $("#btnSearch").click(function () {
            createHddcCjProjectGrid();
        });
        $("#btnReset").click(function () {
            $("#provinceSelect").val("");
            $("#citySelect").val("");
            $("#areaSelect").val("");
            $("#projectNameCondition").val("");
        });
    };
    var createHddcCjProjectGrid = function () {
        $("#hddcCjProjectGrid").datagrid({
            url: getHddcCjProjectController() + "/queryHddcCjProjects",
            //url:getHddcCjProjectController() + "/queryHddcCjProjectsByPersonId/"+"531ec1e7509c4e07b21bb36d254f3ea6",
            method: "GET",
            fitColumns: true,
            autoRowHeight: false,
            columns: [[
                {field: "ck", checkbox: true},
                {
                    field: 'projectId',
                    title: '项目ID',
                    width: '20%',
                    align: 'center',
                },
                {
                    field: 'projectName',
                    title: '项目名称',
                    width: '20%',
                    align: 'center',
                    formatter: function (value, rowData, rowIndex) {
                        return '<a href="#" onclick="_editHddcCjProject(\'' + rowData.id + '\');"> ' + rowData.projectName + ' </a> '
                    }
                },
                {
                    field:'province',sortable:true,
                    title: '省',
                    width: '20%',
                    align: 'center',
                },
                {
                    field:'city',sortable:true,
                    title: '市',
                    width: '20%',
                    align: 'center',
                },
                {
                    field:'area',sortable:true,
                    title: '区（县）',
                    width: '20%',
                    align: 'center',
                },                
                {
                    field: 'personIdsName',
                    title: '人员信息',
                    width: '20%',
                    align: 'center',
                },
                {
                    field: 'projectInfo',
                    title: '项目描述',
                    width: '20%',
                    align: 'center',
                },
            ]],
            toolbar: [{
                iconCls: 'fa fa-plus-circle',
                text: "添加",
                handler: function () {
                    addHddcCjProject();
                }
            }, {
                iconCls: 'fa fa-trash-o',
                text: "删除",
                handler: function () {
                    deleteHddcCjProject();
                }
            }],
            queryParams: {
                province: $("#provinceSelect").val(),
                city: $("#citySelect").val(),
                area: $("#areaSelect").val(),
                projectName: $("#projectNameCondition").val(),
            },
            pagination: true,
            pageSize: 10
        });
    };
    var formValidator = function () {
        $("#hddcCjProjectForm").validate({
            rules: {
                projectId: {
                    required: true,
                },
                projectName: {
                    required: true,
                },
                personIds: {
                    required: true,
                },
                province: {
                    required: true,
                },
                city: {
                    required: true,
                },
                area: {
                    required: true,
                },
                projectInfo: {
                    required: true,
                },
                personIdsName: {
                    required: true,
                }
            },
            messages: {
                projectId: {
                    required: "项目ID不允许为空!",
                },
                projectName: {
                    required: "项目名称不允许为空!",
                },
                province: {
                    required: "省份不允许为空!",
                },
                city: {
                    required: "市不允许为空!",
                },
                area: {
                    required: "区（县）不允许为空!",
                },
                projectInfo: {
                    required: "项目描述不允许为空!",
                },
                personIds: {
                    required: "人员信息不允许为空!",
                },
                personIdsName: {
                    required: "人员信息不允许为空!",
                },
            }
        });
    };
    var getHddcCjProject = function (id) {
        $.ajax({
            url: getHddcCjProjectController() + "/" + id,
            type: "get",
            success: function (data) {
                editProvince(data.province, data.city, data.area);
                Tool.deserialize("hddcCjProjectForm", data);
            }
        });
    };
    /*
        var projectdatas = null;
        var initcreateProject = function () {
            $.ajax({
                url:getHddcCjProjectController() + "/queryAllHddcCjProjects",
                type: "get",
                success: function (data) {
                    projectdatas = data;
                }
            });

        }
     */

    function getCurrentCode(areacode){
        var getCodeAjax = $.ajax({
            type: "GET",
            url: getHddcCjProjectController() + "/projectCode/"+areacode,
            success: function (data) {
                
                $("#projectId").val(data);
            }
        });
    }

    var addHddcCjProject = function () {
        var slidebar = Util.slidebar({
            url: hddcCjProjectFormHtml,
            width: "800px",
            cache: false,
            close: true,
            afterLoad: function () {
                //initProvinceSelectFrom();
                //initCitySelectFrom();
                //initAreaSelectFrom();
                // document.getElementById("projectId").readOnly = false;
                initcreateProvinceForm();
                createPersonIdsUserSelectFrom();
                formValidator();
                
                $("#saveBtn").on("click", function () {
                    var projectdatas = hddccjprojectmethod.getAllProject();
                    var projectName = $("#projectName").val();
                    var projectId = $("#projectId").val();
                    for (var i = 0; i < projectdatas.length; i++) {
                        if (projectdatas[i].projectId == projectId) {
                            Util.alert("项目ID不能重复");
                            return;
                        }
                        if (projectdatas[i].projectName == projectName) {
                            Util.alert("项目名称不能重复");
                            return;
                        }
                    }

                    if ($("#hddcCjProjectForm").valid()) {
                        var data = Tool.serialize("hddcCjProjectForm");
                        
                        $.ajax({
                            url: getHddcCjProjectController()+"/save",
                            contentType: "application/json",
                            data: JSON.stringify(data),
                            type: "post",
                            success: function (data) {
                                Util.alert(data.message);
                                slidebar.close();
                                createHddcCjProjectGrid();
                            }
                        });
                    }
                });
            }
        });
    };
    window._editHddcCjProject = function (hddcCjProjectId) {
        
        var slidebar = Util.slidebar({
            url: hddcCjProjectFormHtml,
            width: "800px",
            cache: false,
            close: true,
            afterLoad: function () {
                //initProvinceSelectFrom();
                //initCitySelectFrom();
                //initAreaSelectFrom();
                
                //$("#projectName").setReadOnly(true);
                //$("#projectId").setReadOnly(false);
                document.getElementById("projectName").readOnly = true;
                document.getElementById("projectId").readOnly = true;
                createPersonIdsUserSelectFrom();
                formValidator();
                getHddcCjProject(hddcCjProjectId);
                $("#saveBtn").on("click", function () {
                    var projectdatas = hddccjprojectmethod.getAllProject();
                    var projectName = $("#projectName").val();
                    var projectId = $("#projectId").val();
                    for (var i = 0; i < projectdatas.length; i++) {
                        if (projectdatas[i].projectId == projectId) {
                            continue;
                        }
                        if (projectdatas[i].projectName == projectName) {
                            Util.alert("项目名称不能重复");
                            return;
                        }
                    }
                    if ($("#hddcCjProjectForm").valid()) {
                        var data = Tool.serialize("hddcCjProjectForm");
                        
                        $.ajax({
                            url: getHddcCjProjectController()+"/update",
                            contentType: "application/json",
                            data: JSON.stringify(data),
                            type: "post",
                            success: function (data) {
                                Util.alert(data.message);
                                slidebar.close();
                                createHddcCjProjectGrid();
                            }
                        });
                    }
                });
            }
        });
    };
    var deleteHddcCjProject = function () {
        var rows = $("#hddcCjProjectGrid").datagrid("getSelections");
        if (rows == null || rows.length == 0) {
            Util.alert("请选择一行数据!");
            return;
        }
        Util.confirm("删除项目会将该项目下所有任务和表单删除，是否继续?", function () {
            Util.confirm("确认删除选中的项目?",function () {
                var ids = "";
                $.each(rows, function (i, row) {
                    ids += row.id + ",";

                });
                ids = ids.substr(0, ids.length - 1);
                $.ajax({
                    url: getHddcCjProjectController()+"/delete",
                    contentType:"application/json",
                    data:ids,
                    type: "post",
                    success: function (data) {
                        createHddcCjProjectGrid();
                        Util.alert(data.message);
                    }
                });
            },function () {
                return;
            })

        }, function () {
            return;
        });

    };

    var initcreateProvince = function () {
        var html = "";
        $("#citySelect").append(html);
        $("#areaSelect").append(html);
        $.ajax({
            url: getServer() + "/divisions/root/subdivisions",
            contentType: "application/json",
            type: "get",
            success: function (data) {
                $.each(data, function (idx, item) {
                    html += "<option value='" + item.divisionName + "' exid='" + item.divisionId + "'>" + item.divisionName + "</option>";
                });
                $("#provinceSelect").append(html);
            }
        });
        $("#provinceSelect").change(function () {
            var html = '<option value="" disabled selected style="display:none;">请选择</option>';
            $("#citySelect option").remove();
            $("#citySelect").append(html);
            $("#areaSelect option").remove();
            $("#areaSelect").append(html);
            var divisionId = $(this).find("option:selected").attr("exid");
            if ($(this).val() == "北京市" || $(this).val() == "天津市" || $(this).val() == "上海市" || $(this).val() == "重庆市") {
                $("#citySelect").append("<option value='" + $(this).val() + "' exid='" + divisionId + "'>" + $(this).val() + "</option>");
                return;
            }
            $.ajax({
                url: getServer() + "/divisions/" + divisionId + "/subdivisions",
                contentType: "application/json",
                type: "get",
                success: function (data) {
                    $.each(data, function (idx, item) {
                        html += "<option value='" + item.divisionName + "' exid='" + item.divisionId + "'>" + item.divisionName + "</option>";
                    });
                    $("#citySelect").append(html);
                }
            });
        });
        $("#citySelect").change(function () {
            if ($(this).val() == "") return;
            var html = '<option value="" disabled selected style="display:none;">请选择</option>';
            $("#areaSelect option").remove();
            $("#areaSelect").append(html);
            var divisionId = $(this).find("option:selected").attr("exid");
            $.ajax({
                url: getServer() + "/divisions/" + divisionId + "/subdivisions",
                contentType: "application/json",
                type: "get",
                success: function (data) {
                    $.each(data, function (idx, item) {
                        html += "<option value='" + item.divisionName + "' exid='" + item.divisionId + "'>" + item.divisionName + "</option>";
                    });
                    $("#areaSelect").append(html);
                }
            });
        });
    }
    var initcreateProvinceForm = function () {
        var html = "";
        $("#city").append(html);
        $("#area").append(html);
        $.ajax({
            url: getServer() + "/divisions/root/subdivisions",
            contentType: "application/json",
            type: "get",
            success: function (data) {
                $.each(data, function (idx, item) {
                    html += "<option value='" + item.divisionName + "' exid='" + item.divisionId + "'>" + item.divisionName + "</option>";
                });
                $("#province").append(html);
            }
        });
        $("#province").change(function () {
            var html = '<option value="" disabled selected style="display:none;">请选择</option>';
            $("#city option").remove();
            $("#city").append(html);
            $("#area option").remove();
            $("#area").append(html);
            var divisionId = $(this).find("option:selected").attr("exid");
            if ($(this).val() == "北京市" || $(this).val() == "天津市" || $(this).val() == "上海市" || $(this).val() == "重庆市") {
                $("#city").append("<option value='" + $(this).val() + "' exid='" + divisionId + "'>" + $(this).val() + "</option>");
                return;
            }
            $.ajax({
                url: getServer() + "/divisions/" + divisionId + "/subdivisions",
                contentType: "application/json",
                type: "get",
                success: function (data) {
                    $.each(data, function (idx, item) {
                        html += "<option value='" + item.divisionName + "' exid='" + item.divisionId + "'>" + item.divisionName + "</option>";
                    });
                    $("#city").append(html);
                }
            });
        });
        var areaNames=[];
        var areaCodes=[];
        $("#city").change(function () {
            if ($(this).val() == "") return;
            var html = '<option value="" disabled selected style="display:none;">请选择</option>';
            $("#area option").remove();
            $("#area").append(html);
            var divisionId = $(this).find("option:selected").attr("exid");
            $.ajax({
                url: getServer() + "/divisions/" + divisionId + "/subdivisions",
                contentType: "application/json",
                type: "get",
                success: function (data) {
                    $.each(data, function (idx, item) {
                        areaNames.push(item.divisionName);
                        areaCodes.push(item.divisionCode);
                        html += "<option value='" + item.divisionName + "' exid='" + item.divisionId + "'>" + item.divisionName + "</option>";
                    });
                    $("#area").append(html);
                }
            });
        });
        $("#area").change(function () {
            var areaname=$('#area').val();
            var index = -1;
            for(var i =0;i<areaNames.length;i++){
                if(areaname==areaNames[i]){
                    index=i;
                    break;
                }
            }
            if(index>=0){
                var areacode=areaCodes[index];
                getCurrentCode(areacode);
            }
            
        });
    }

    var editProvince = function (Province, City, Area) {
        
        var html = "";
        $("#city").append(html);
        $("#area").append(html);
        $.ajax({
            url: getServer() + "/divisions/root/subdivisions",
            contentType: "application/json",
            type: "get",
            success: function (data) {
                $.each(data, function (idx, item) {
                    if (item.divisionName == Province) {
                        
                        var divisionId = item.divisionId;
                        var htmlCity = '';
                        if (Province == "北京市" || Province == "天津市" || Province == "上海市" || Province == "重庆市") {
                            $("#city").append("<option value='" + Province + "' exid='" + divisionId + "'>" + Province + "</option>");
                            $('#city').val(City);
                            var htmlArea = '';
                            $.ajax({
                                url: getServer() + "/divisions/" + divisionId + "/subdivisions",
                                contentType: "application/json",
                                type: "get",
                                success: function (data) {
                                    $.each(data, function (idx, item) {
                                        htmlArea += "<option value='" + item.divisionName + "' exid='" + item.divisionId + "'>" + item.divisionName + "</option>";
                                    });
                                    $("#area").append(htmlArea);
                                    $('#area').val(Area);
                                }
                            });

                        } else {
                            $.ajax({
                                url: getServer() + "/divisions/" + divisionId + "/subdivisions",
                                contentType: "application/json",
                                type: "get",
                                success: function (data) {
                                    
                                    $.each(data, function (idx, item) {
                                        if (item.divisionName == City) {
                                            var divisionId = item.divisionId;
                                            var htmlArea = '';
                                            $.ajax({
                                                url: getServer() + "/divisions/" + divisionId + "/subdivisions",
                                                contentType: "application/json",
                                                type: "get",
                                                success: function (data) {
                                                    $.each(data, function (idx, item) {
                                                        htmlArea += "<option value='" + item.divisionName + "' exid='" + item.divisionId + "'>" + item.divisionName + "</option>";
                                                    });
                                                    $("#area").append(htmlArea);
                                                    $('#area').val(Area);
                                                }
                                            });
                                        }
                                        htmlCity += "<option value='" + item.divisionName + "' exid='" + item.divisionId + "'>" + item.divisionName + "</option>";
                                    });
                                    $("#city").append(htmlCity);
                                    $('#city').val(City);
                                }
                            });
                        }
                    }
                    html += "<option value='" + item.divisionName + "' exid='" + item.divisionId + "'>" + item.divisionName + "</option>";
                });
                $("#province").append(html);
                $('#province').val(Province);
            }
        });
        $("#province").change(function () {
            var html = '<option value="" disabled selected style="display:none;">请选择</option>';
            $("#city option").remove();
            $("#city").append(html);
            $("#area option").remove();
            $("#area").append(html);
            var divisionId = $(this).find("option:selected").attr("exid");
            if ($(this).val() == "北京市" || $(this).val() == "天津市" || $(this).val() == "上海市" || $(this).val() == "重庆市") {
                $("#city").append("<option value='" + $(this).val() + "' exid='" + divisionId + "'>" + $(this).val() + "</option>");
                return;
            }
            $.ajax({
                url: getServer() + "/divisions/" + divisionId + "/subdivisions",
                contentType: "application/json",
                type: "get",
                success: function (data) {
                    $.each(data, function (idx, item) {
                        html += "<option value='" + item.divisionName + "' exid='" + item.divisionId + "'>" + item.divisionName + "</option>";
                    });
                    $("#city").append(html);
                }
            });
        });
        $("#city").change(function () {
            if ($(this).val() == "") return;
            var html = '<option value="" disabled selected style="display:none;">请选择</option>';
            $("#area option").remove();
            $("#area").append(html);
            var divisionId = $(this).find("option:selected").attr("exid");
            $.ajax({
                url: getServer() + "/divisions/" + divisionId + "/subdivisions",
                contentType: "application/json",
                type: "get",
                success: function (data) {
                    $.each(data, function (idx, item) {
                        html += "<option value='" + item.divisionName + "' exid='" + item.divisionId + "'>" + item.divisionName + "</option>";
                    });
                    $("#area").append(html);
                }
            });
        });
    }

    return {
        init: init
    };
});
